package com.weimei.conversionTreasure.viewModel;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import androidx.annotation.NonNull;

import com.gtdev5.geetolsdk.mylibrary.beans.LoginInfoBean;
import com.gtdev5.geetolsdk.mylibrary.beans.UpdateBean;
import com.gtdev5.geetolsdk.mylibrary.callback.BaseCallback;
import com.gtdev5.geetolsdk.mylibrary.http.Base64HttpUtils;
import com.gtdev5.geetolsdk.mylibrary.http.HttpUtils;
import com.gtdev5.geetolsdk.mylibrary.util.DataSaveUtils;
import com.gtdev5.geetolsdk.mylibrary.util.MapUtils;
import com.gtdev5.geetolsdk.mylibrary.util.Utils;
import com.lxj.xpopup.XPopup;
import com.weimei.conversionTreasure.activity.WebActivity;
import com.weimei.conversionTreasure.app.AppConfig;
import com.weimei.conversionTreasure.http.ApiService;
import com.weimei.conversionTreasure.http.Repository;
import com.weimei.conversionTreasure.http.entity.BaseResult;
import com.weimei.conversionTreasure.http.entity.UserBean;
import com.weimei.conversionTreasure.utils.UserUtils;
import com.weimei.conversionTreasure.utils.ValidateUtils;
import com.weimei.conversionTreasure.weight.DialogUtils;
import com.weimei.conversionTreasure.weight.LoginPop;

import java.util.HashMap;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import okhttp3.Request;
import okhttp3.Response;

public class LoginVM extends BaseViewModel<Repository> {
    Activity mContext;
    private String userName = "";
    private String userid = "";
    private String userIcon = "";
    private Map<String, String> loginMap;


    public void setmContext(Activity mContext) {
        this.mContext = mContext;
    }

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public LoginVM(@NonNull Application application, Repository model) {
        super(application, model);
    }

    public class UIChangeObservable {
        //开关观察者
        public SingleLiveEvent<Boolean> pSwitchEvent = new SingleLiveEvent<>();
    }

    public BindingCommand SwitchOnClickCommand = new BindingCommand(() -> {
        //让观察者的数据改变,逻辑从ViewModel层转到View层，在View层的监听则会被调用
        uc.pSwitchEvent.setValue(uc.pSwitchEvent.getValue() == null || !uc.pSwitchEvent.getValue());
    });


    public BindingCommand QQLogin = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (uc.pSwitchEvent.getValue() == null) {
                ToastUtils.showShort("请阅读并同意《用户协议》与《隐私政策》");
            } else {
                if (uc.pSwitchEvent.getValue()) {
                    thirdLogin("qq");
                } else {
                    ToastUtils.showShort("请阅读并同意《用户协议》与《隐私政策》");
                }
            }
        }
    });

    private void thirdLogin(String flag) {
        DialogUtils.showLoading(mContext,"登录中...");
        ToastUtils.showShort("正在打开第三方应用");
        Platform plat;
        if ("qq".equals(flag)) {
            plat = ShareSDK.getPlatform(QQ.NAME);
        } else {
            plat = ShareSDK.getPlatform(Wechat.NAME);
        }
        //移除授权状态和本地缓存，下次授权会重新授权
        plat.removeAccount(true);
        //SSO授权，传false默认是客户端授权
        plat.SSOSetting(false);
        //授权回调监听，监听oncomplete，onerror，oncancel三种状态

        plat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                userName = ValidateUtils.isCheck(platform.getDb().getUserName());
                userid = ValidateUtils.isCheck(platform.getDb().getUserId());
                userIcon = ValidateUtils.isCheck(platform.getDb().getUserIcon());
                loginMap = MapUtils.getWeChatLogin(userid, userName, platform.getDb().getUserGender(), userIcon);
                login(flag);
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {

            }

            @Override
            public void onCancel(Platform platform, int i) {

            }
        });
        //要数据不要功能，主要体现在不会重复出现授权界面
        plat.showUser(null);
    }

    public BindingCommand WXLogin = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (uc.pSwitchEvent.getValue() == null) {
                ToastUtils.showShort("请阅读并同意《用户协议》与《隐私政策》");
            } else {
                if (uc.pSwitchEvent.getValue()) {
                    thirdLogin("wx");
                } else {
                    ToastUtils.showShort("请阅读并同意《用户协议》与《隐私政策》");
                }
            }
        }
    });


    public BindingCommand test = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (uc.pSwitchEvent.getValue() == null) {
                ToastUtils.showShort("请阅读并同意《用户协议》与《隐私政策》");
            } else {
                new XPopup.Builder(mContext).moveUpToKeyboard(false)//如果不加这个，评论弹窗会移动到软键盘上面
                        .enableDrag(true).asCustom(new LoginPop(mContext, (s) -> {
                                    if (s) {
                                        userid = "geetol10086";
                                        userName = "测试账号";
                                        userIcon = "https://thirdwx.qlogo.cn/mmopen/vi_32/Hj3bU4EXunkWb2lVB7Siczr4APU888dG8Kgs8dmCAlVfARfib2yib2YyQequCbvicImso7MKPb3r5r6znaNkexyJNqu8Uib0F318OiaL8pPYpRyUo/132";

                                        loginMap = MapUtils.getWeChatLogin(userid, userName, "", userIcon);
                                        login("wx");

                                    }
                                })
                        ).show();
            }


        }
    });


    public BindingCommand YHXY = new BindingCommand(() -> {
        Bundle bundle = new Bundle();
        bundle.putString("flag", "YHXY");
        startActivity(WebActivity.class, bundle);
    });


    public BindingCommand YSZC = new BindingCommand(() -> {
        Bundle bundle = new Bundle();
        bundle.putString("flag", "YSZC");
        startActivity(WebActivity.class, bundle);
    });

    private void login(String flag) {
        if (flag.equals("qq")) {
            HttpUtils.getInstance().post(ApiService.GT_QQ_LOGIN, loginMap, new BaseCallback<LoginInfoBean>() {
                @Override
                public void onRequestBefore() {

                }

                @Override
                public void onFailure(Request request, Exception e) {
                    e.printStackTrace();
                }

                @Override
                public void onSuccess(Response response, LoginInfoBean loginInfoBean) {

                    if (loginInfoBean.isIssucc()){
                        model.setLogin(loginInfoBean);
                        GTUpdate(loginInfoBean);
                    }else {
                        ToastUtils.showShort(loginInfoBean.getCode());
                    }
                }

                @Override
                public void onError(Response response, int errorCode, Exception e) {
                }
            });
        } else {
            HttpUtils.getInstance().post(ApiService.GT_WECHAT_LOGIN, loginMap, new BaseCallback<LoginInfoBean>() {

                @Override
                public void onRequestBefore() {

                }

                @Override
                public void onFailure(Request request, Exception e) {
                    e.printStackTrace();
                }

                @Override
                public void onSuccess(Response response, LoginInfoBean loginInfoBean) {
                    if (loginInfoBean.isIssucc()){
                        model.setLogin(loginInfoBean);
                        GTUpdate(loginInfoBean);
                    }else {
                        ToastUtils.showShort(loginInfoBean.getCode());
                    }


                }

                @Override
                public void onError(Response response, int errorCode, Exception e) {
                }
            });
        }
    }

    private void GTUpdate(LoginInfoBean loginInfoBean) {
        UserUtils.setUser(loginInfoBean.getData());
        Utils.setLoginInfo(loginInfoBean.getData().getUser_id(),
                loginInfoBean.getData().getUkey(),
                loginInfoBean.getData().getHeadimg());
        Base64HttpUtils.getInstance().postUpdate(new BaseCallback<UpdateBean>() {
            @Override
            public void onRequestBefore() {
            }

            @Override
            public void onFailure(Request request, Exception e) {
                DialogUtils.stopLoading();
            }

            @Override
            public void onSuccess(Response response, UpdateBean o) {
                DialogUtils.stopLoading();
                if (o != null && o.getIssucc()) {
                    UserUtils.setVip(o.getVip());
                    DataSaveUtils.getInstance().saveAppData(o);
                    finish();
                }
            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {
                DialogUtils.stopLoading();
            }
        });

    }
}
